package com.nowcoder.community.controller.interceptor;

import com.nowcoder.community.annotation.LoginRequire;
import com.nowcoder.community.annotation.RestLoginRequire;
import com.nowcoder.community.util.HostHolder;
import com.nowcoder.community.util.JsonBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * controller鉴权, user注入.
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Autowired
    HostHolder hostHolder;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod hm = (HandlerMethod) handler;
            // 未登录状态
            if (hostHolder.getUser() == null) {
                if (hm.hasMethodAnnotation(LoginRequire.class)) {
                    response.sendRedirect(request.getContextPath() + "/login");
                    return false;
                }

                if (hm.hasMethodAnnotation(RestLoginRequire.class)) {
                    response.setContentType("application/json");
                    response.setCharacterEncoding("UTF-8");
                    try(PrintWriter writer = response.getWriter()) {
                        writer.print(JsonBody.error("请登录后再试.").toJson());
                    }
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if (handler instanceof HandlerMethod) {
            if (modelAndView != null && modelAndView.getModel().get("user") == null) {
                modelAndView.getModel().put("user", hostHolder.getUser());
            }
        }

        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }
}
